package org.example.struct.array2;

import com.alibaba.fastjson.JSON;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author liyishan
 * @date 2023/10/10 09:22
 * @apiNote
 */

public class Test00442FindDuplicates {

    public static void main(String[] args) {
        int[] nums = {4,3,2,7,8,2,3,1};
        List<Integer> result = test2(nums);
        System.out.println(JSON.toJSON(result));
    }


    public static List<Integer> test(int[] nums) {
        List<Integer> result = new ArrayList<>();
        Arrays.sort(nums);
        for(int  i = 1; i < nums.length; i++){
            if(nums[i] == nums[i-1]) {
                result.add(nums[i]);
            }
        }
        return result;
    }


    public static List<Integer> test1(int[] nums) {
        List<Integer> result = new ArrayList<>();
        int n = nums.length;
        for(int i = 0; i < n; i++){
            int x =Math.abs(nums[i]);
            if(nums[x-1] > 0){
                nums[x-1] = -nums[x-1];
            }else{
                result.add(x);
            }
        }
        return result;
    }


    public static List<Integer> test2(int[] nums) {
        List<Integer> result = new ArrayList<>();
        int n = nums.length;
        for(int i = 0; i < n; i++){
            while(nums[i] != nums[nums[i] - 1 ]){
                swap(nums, i, nums[i] - 1);
            }
        }
        for(int i = 0; i < n; i++){
            if(nums[i] -1 != i){
                result.add(nums[i]);
            }
        }
        return result;
    }

    public static void swap(int[] nums, int i, int j){
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }
}
